package com.warrantyhotel.android.ui;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;

import com.warrantyhotel.android.R;
import com.warrantyhotel.android.adapter.NearbyStoresAdapter;
import com.warrantyhotel.android.db.QueriesCodes;
import com.warrantyhotel.android.db.WarrantyHotelDBSchema.FindStoresTable;
import com.warrantyhotel.android.model.Keys;
import com.warrantyhotel.android.util.NotifyingAsyncQueryHandler;
import com.warrantyhotel.android.util.ToastUtil;
import com.warrantyhotel.android.util.NotifyingAsyncQueryHandler.AsyncQueryListener;

public class NearbyStores extends Activity implements AsyncQueryListener, OnItemClickListener {

	private NotifyingAsyncQueryHandler mHandler;
	private ListView listView;
	private Button button;
	private NearbyStoresAdapter mAdapterl;
	private final static int redirectOnMap = 33;
	private Cursor cursor;
	private Bundle bundle;

	public static String RIGHT_BOTTOM_LAT = "right_bottom_lat";
	public static String RIGHT_BOTTOM_LNG = "right_bottom_lng";
	public static String LEFT_BOTTOM_LAT = "left_bottom_lat";
	public static String LEFT_BOTTOM_LNG = "left_bottom_lng";
	public static String LEFT_TOP_LAT = "left_top_lat";
	public static String LEFT_TOP_LNG = "left_top_lng";
	public static String RIGHT_TOP_LAT = "right_top_lat";
	public static String RIGHT_TOP_LNG = "right_top_lng";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.nearby_stores);
		listView = (ListView) findViewById(R.id.nearby_stores_list);
		button = (Button) findViewById(R.id.clear_mask_stores);
		listView.setOnItemClickListener(this);

		mHandler = new NotifyingAsyncQueryHandler(getContentResolver(), this);

		bundle = getIntent().getExtras();

		String retainFilter = null;
		if (bundle != null && bundle.containsKey(Keys._retailIdFilter)) {
			retainFilter = bundle.getString(Keys._retailIdFilter);
		}

		if (bundle != null && bundle.containsKey(Keys._query)) {
			String query = getIntent().getStringExtra(Keys._query);
			nearbyStoresRetrievingFromDB(FindStoresTable.NAME + " like '%" + query + "%'", bundle);
			button.setVisibility(View.VISIBLE);
		} else {
			nearbyStoresRetrievingFromDB(retainFilter, bundle);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.nearby_stores, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.go_to_map:
			finish();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	public void onClearFilter(View view) {
		nearbyStoresRetrievingFromDB(null, bundle);
		view.setVisibility(View.GONE);
	}

	private void nearbyStoresRetrievingFromDB(String name, Bundle bundle) {
		String retailStoreId = bundle.getString(Keys._retailStoreId);
		String selection = null;

		if (bundle.containsKey(LEFT_BOTTOM_LAT) && bundle.containsKey(LEFT_TOP_LAT)) {
			selection = FindStoresTable.LOCATION_LATITUDE + " > " + bundle.getDouble(LEFT_BOTTOM_LAT) + " AND " + FindStoresTable.LOCATION_LATITUDE + " < "
					+ bundle.getDouble(LEFT_TOP_LAT) + " AND " + FindStoresTable.LOCATION_LONGITUDE + " > " + bundle.getDouble(LEFT_BOTTOM_LNG) + " AND "
					+ FindStoresTable.LOCATION_LONGITUDE + " < " + bundle.getDouble(RIGHT_BOTTOM_LNG);
		}

		if (name != null) {
			selection = (TextUtils.isEmpty(selection)) ? name : selection + " AND " + FindStoresTable.RETAIL_ID + " = '" + name + "'";
		}

		if (retailStoreId != null)
			selection = selection + " AND " + FindStoresTable.RETAIL_STORE_ID + " = '" + retailStoreId + "'";

		String[] projectionNearbyStores = { FindStoresTable._ID, FindStoresTable.NAME, FindStoresTable.LOCATION_LATITUDE, FindStoresTable.LOCATION_LONGITUDE,
				FindStoresTable.THUMBNAIL, FindStoresTable.RETAIL_STORE_ID, FindStoresTable.BANNER, FindStoresTable.SERVICE_EMAIL, FindStoresTable.POI };
		mHandler.startQuery(QueriesCodes.NEARBY_STORES, FindStoresTable.CONTENT_URI, projectionNearbyStores, selection, null, null);
	}

	@Override
	public void onQueryComplete(int token, Object cookie, Cursor cursor) {
		switch (token) {
		case QueriesCodes.NEARBY_STORES:
			if (cursor != null) {
				startManagingCursor(cursor);
				this.cursor = cursor;
				mAdapterl = new NearbyStoresAdapter(NearbyStores.this, cursor);
				listView.setAdapter(mAdapterl);
			}
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
		final Intent intent = new Intent(getApplicationContext(), NearbyStoresDetail.class);
		if (cursor.moveToPosition(position)) {
			boolean isPOI = 1 == cursor.getInt(cursor.getColumnIndex(FindStoresTable.POI));
			String name = cursor.getString(cursor.getColumnIndex(FindStoresTable.NAME));
			if (!isPOI) {
				String RetailStoreId = cursor.getString(cursor.getColumnIndex(FindStoresTable.RETAIL_STORE_ID));
				String bannerUrl = cursor.getString(cursor.getColumnIndex(FindStoresTable.BANNER));
				intent.putExtra(Keys._retailStoreId, RetailStoreId);
				intent.putExtra(Keys._id, id);
				intent.putExtra(Keys.banner, bannerUrl);
				intent.putExtra(Keys.needRedirect, true);
				startActivityForResult(intent, redirectOnMap);

			} else {
				ToastUtil.showText(this, name + "\n" + getString(R.string.poi));
			}
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case redirectOnMap:
				Intent intent = new Intent();
				intent.putExtra(Keys.latitude, data.getDoubleExtra(Keys.latitude, 0d));
				intent.putExtra(Keys.longtitude, data.getDoubleExtra(Keys.longtitude, 0d));
				setResult(RESULT_OK, intent);
				finish();
				break;

			default:
				break;
			}
		}
	}

}
